const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const User = require('../db/model/UserModel')
const Redis = require('../redis/Redis')
const Md5 = require('blueimp-md5')
const { mySend, Vtoken, checkParams, test, getRandom } = require('../utils/index')


router.post('/register', (req, res) => {
  const { username, password, phone, code } = req.body

  if (!username || !password || !phone || !code) {
    return mySend(res, 1, '用户名/密码/手机号/验证码不能为空')
  }

  if (username.length < 4 || username.length > 12) {
    return mySend(res, 1, '用户名长度需要4-12位之间')
  }

  if (password.length < 4 || password.length > 12) {
    return mySend(res, 1, '密码长度需要4-12位之间')
  }

  if (!(/^1[3456789]\d{9}$/.test(phone))) {
    return mySend(res, 1, '手机号不正确')
  }
  User.findOne({ username }).then((docs) => {
    if (docs) {
      return mySend(res, 1, '用户名已存在')
    } else {
      User.findOne({ phone }).then((docs2) => {
        if (docs2) {
          return mySend(res, 1, '手机号已存在')
        } else {
          Redis.get(phone).then((result) => {
            if (!result) {
              return mySend(res, 1, '请先获取验证码')
            }
            if (code !== result) {
              return mySend(res, 1, '验证码错误')
            }

            let siteKey = 'my_space'
            let encodePassword = Md5(password + siteKey)
            User.insertMany({ username, password: encodePassword, phone })
              .then(() => {
                return mySend(res, 0, '注册成功')
              })
              .catch(error => {
                return mySend(res, -1, '注册失败,服务器内部错误', error)
              })

          }).catch(err => {
            return mySend(res, -1, '注册失败,服务器内部错误', err)
          })
        }
      })
    }
  })
})

router.post('/login', (req, res) => {
  const { username, password } = req.body

  if (!username) {
    return mySend(res, 1, '请输入用户名')
  }
  if (!password) {
    return mySend(res, 1, '请输入密码')
  }
  User.findOne({ $or: [{ username }, { phone: username }] }, { __v: 0 }).then(doc => {
    if (!doc) {
      return mySend(res, 1, '用户名或手机号不存在')
    }
    let siteKey = 'my_space'
    let encodePassword = Md5(password + siteKey)
    if (doc.password !== encodePassword) {
      return mySend(res, 1, '密码错误')
    }

    let user = doc.toObject()
    delete user.password
    let token = Md5(username + siteKey + getRandom(1000, 9999));
    Redis.set(token, JSON.stringify(user), 60 * 60 * 24, 1).then((result) => {
      if (result !== 'OK') {
        return mySend(res, -1, '存入redis有误', result)
      }
      user.token = token
      return mySend(res, 0, '登录成功', user)
    })
  })
})

router.post('/logout', async (req, res) => {
  const { token } = req.body
  const user = await Vtoken(token)
  if (!user) {
    return mySend(res, 314, 'token不存在或已过期')
  }
  Redis.set(token, '', 0, 1).then(result => {
    if (result !== 'OK') {
      return mySend(res, -1, '存入redis有误', result)
    } else {
      mySend(res, 0, '退出成功')
    }
  })
})

router.post('/forget', (req, res) => {
  const { username, code, password } = req.body
  if (!username) {
    return mySend(res, 1, '请输入用户名或手机号')
  }
  if (!password) {
    return mySend(res, 1, '请输入新密码')
  }
  if (!code) {
    return mySend(res, 1, '请输入验证码')
  }

  User.findOne({ $or: [{ username }, { phone: username }] }).then(doc => {
    if (!doc) {
      return mySend(res, 1, '用户名或手机号不存在')
    }

    const { phone } = doc

    Redis.get(phone).then((result) => {
      if (!result) {
        return mySend(res, 1, '请先获取验证码')
      }

      if (code !== result) {
        return mySend(res, 1, '验证码错误')
      }

      let siteKey = 'my_space'
      let encodePassword = Md5(password + siteKey)

      User.update({ _id: doc._id }, { password: encodePassword }).then(doc2 => {
        return mySend(res, 0, '修改成功', doc2)
      }).catch(err2 => {
        return mySend(res, 1, '修改失败', err2)
      })

    }).catch(err => {
      return mySend(res, -1, '存入reids错误', err)
    })

  })
})

router.post('/updatePassword', async (req, res) => {
  const { password, newPassword, token } = req.body
  const checked = checkParams({ password, newPassword, token })
  if (checked) return mySend(res, 1, checked)
  const user = await Vtoken(token)
  if (!user) {
    return mySend(res, 314, 'token不存在或已过期')
  }
  let siteKey = 'my_space'
  let encodePassword = Md5(password + siteKey)
  User.findOne({ $and: [{ username: user.username }, { password: encodePassword }] }).then(doc => {
    if (!doc) {
      return mySend(res, 1, '密码错误')
    }

    
    let encodeNewPassword = Md5(newPassword + siteKey)
    User.update({_id: user._id}, { password: encodeNewPassword })
      .then(() => {
        return mySend(res, 0, '修改成功')
      }).catch(err => {
        return mySend(res, 1, '修改失败', err)
      })
  })
})

router.post('/update', async (req, res) => {
  const { status, role, token, targetId } = req.body
  const user = await Vtoken(token)
  if (!user) {
    return mySend(res, 314, 'token不存在或已过期')
  }

  if (!status && !role) {
    return mySend(res, 1, '参数有误')
  }

  User.findOne({ _id: user._id, role: 1 }).then(doc => {
    if (!doc) {
      return mySend(res, 1, '你的权限不足')
    }
    let upDateData = {}
    if (status) {
      upDateData.status = status * 1
    }
    if (role) {
      upDateData.role = role * 1
    }
    User.update({ _id: targetId }, upDateData).then(doc1 => {
      if (doc1) {
        return mySend(res, 0, '修改成功')
      } else {
        return mySend(res, 1, '修改失败')
      }
    }).catch(err1 => {
      return mySend(res, 1, '修改失败', err1)
    })

  }).catch(err => {
    return mySend(res, 1, '修改失败', err)
  })

})

router.post('/userList', async (req, res) => {
  const { token, current = 1, size = 10 } = req.body
  const user = await Vtoken(token)
  if (!user) {
    return mySend(res, 314, 'token不存在或已过期')
  }
  User.findOne({ _id: user._id, role: 1 }).then(doc => {
    if (!doc) {
      return mySend(res, 1, '你的权限不能查看用户列表')
    }

    User.countDocuments().then(total => {
      User.find({}, { password: 0, __v: 0 })
        .sort({ role: 1, ctime: -1 })
        .skip((current - 1) * size)
        .limit(size).then(docs => {
          let users = docs || []
          let body = {
            total,
            current,
            size,
            list: users
          }
          return mySend(res, 0, 'success', body)
        }).catch(err2 => {
          return mySend(res, 1, '服务器错误', err2)
        })
    }).catch(err1 => {
      return mySend(res, 1, '服务器错误', err1)
    })


  }).catch(err => {
    return mySend(res, 1, '服务器错误', err)
  })
})

router.post('/userInfo', async (req, res) => {
  const { token } = req.body
  const user = await Vtoken(token)

  if (!user) {
    return mySend(res, 314, 'token不存在或已过期')
  }
  User.find({ _id: user._id }, { _id: 0, password: 0 }).then(doc => {
    return mySend(res, 0, 'success', doc)
  }).catch(err => {
    return mySend(res, 1, '服务器出错', err)
  })
})

router.get('/test', (req, res) => {
  const { a, b } = req.body
  // console.log(req.body)
  // console.log(22222)
  // test(res, { a, b })
  // console.log(11111)
  res.send({ code: 0, msg: 'test ok' })
  // if(checked) return mySend(res, 1, checked)

})

// 修改为管理员
// router.get('/updateUserToManage', (req, res) => {
//   User.updateOne({ phone: 13078253870 }, {role: 1}).then(doc => {
//     if (doc) {
//       return mySend(res, 0, '修改成功')
//     } else {
//       return mySend(res, 1, '修改失败')
//     }
//   }).catch(err1 => {
//     return mySend(res, 1, '修改失败', err1)
//   })
// })

module.exports = router